load("js/luaclient.js");
load("js/keys_comm.js");
/**
 * 抓取北京信用卡信息
 * @type {{}}
 */
var crawCraditData = {
    /**
     * 抓取信用卡基本信息
     * @param creditCardAllData
     */
    crawlBillInfoData : function(creditCardAllData){
        logger.info("{},北京银行信用卡基本信息开始抓取", context.get(LUA_TASK_KEY));
        try {
            var accountInfoHtml = context.get("account_info");
            var accountDoc = Jsoup.parse(accountInfoHtml);
            // 持卡人
            var name = accountDoc
                .select("#main > div.pt10 > div.f14 > table > tbody > tr:nth-child(1) > td:nth-child(2)").text()
                .trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");
            // 信用卡额度
            var creditLimit = accountDoc.select("#ax_creditLimit")[0].text().trim().replaceAll(",", "");// 信用卡额度
            // 信用卡可用额度
            var balance = accountDoc.select("#ax_avLimit")[0].text().trim().replaceAll(",", "");
            // 信用卡现金总额度
            var cashLimit = accountDoc.select("#ax_caLimit")[0].text().trim().replaceAll(",", "");
            // 信用卡现金可用额度
            // String cashBalance = zhuanghuDoc.select("").text().trim();
            // 账单日
            billDate = accountDoc.select("#ax_cyclNbr").text().trim();
            context.put("billDay",billDate);
            // logger.info("持卡人:{}", name);
            creditCardAllData.setCardId(UUID.randomUUID().toString());
            creditCardAllData.setCardType("信用卡");
            creditCardAllData.setBankName("北京银行");
            creditCardAllData.setDeposits(new ArrayList());// 这个是借记卡才有的
            creditCardAllData.setNameOnCard(name);// 持卡人
            creditCardAllData.setFullCardNum(cardListFunc(accountDoc));// 完整卡号
            creditCardAllData.setCardNum(cardNum(accountDoc));// 卡号后四位
            creditCardAllData.setCreditLimit(stringToBigDecimal(creditLimit));// 信用卡额度
            creditCardAllData.setBalance(stringToBigDecimal(balance));// 信用卡可用额度
            creditCardAllData.setCashLimit(stringToBigDecimal(cashLimit));// 信用卡现金总额度
            creditCardAllData.setCashBalance(null);
            creditCardAllData.setOpenBank("");
        }catch (e) {
            logger.error("{}，北京银行信用卡基本信息抓取异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtException(context, e);
        }
    },
    /**
     * 抓取用户已出账单数据s
     * @param creditCardAllData
     */
    crawlBillDetails : function(creditCardAllData,billAllData,singleMonth,billDate,doneType){
        try {
            var billDateEveryHtml;
            billAllData.setBillId(UUID.randomUUID().toString());
            billAllData.setBankName("北京银行");
            // 信用额度相关
            billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
            billAllData.setCashLimit(creditCardAllData.getCashLimit());
            if("UNDONE" == doneType){
                logger.info("北京银行信用卡,任务{},未出账单抓取", context.get(LUA_TASK_KEY));
                var monthSinple = new SimpleDateFormat("YYYY-MM");
                var calendar = Calendar.getInstance();
                var day = calendar.get(Calendar.DAY_OF_MONTH);
                day = Integer.parseInt(day);
                var billOutDate = "";
                if (billDate !== ""&& null !== billDate) {
                    if (day > Integer.parseInt(billDate)) {
                        calendar.add(Calendar.MONTH, 1);
                    }
                    billOutDate = monthSinple.format(calendar.getTime());
                }
                billAllData.setBillMonth(billOutDate);
                billAllData.setBillDate(getDate(billOutDate + "-" + billDate,"yyyy-MM-dd"));
                billAllData.setBillType("UNDONE");
                billDateEveryHtml = context.get(doneType +"_billdata");
                var unDoneDoc = Jsoup.parse(billDateEveryHtml);
                // 本期帐单金额
                var newCharges = unDoneDoc.select("td.value:nth-child(2)")[0].text().trim().replaceAll(",", "");
                billAllData.setNewCharges(stringToBigDecimal(newCharges));// 本期账单金额
            }else {
                billAllData.setBillType("DONE");
                billAllData.setBillMonth(singleMonth);// yyyy-MM
                billAllData.setBillDate(getDate(singleMonth + "-" + billDate,"yyyy-MM-dd"));
                // singleMonth = singleMonth.replaceAll("-", "");
                billDateEveryHtml = context.get("bill_" + doneType +"_"+ singleMonth);
                var billDateEveryDoc = Jsoup.parse(billDateEveryHtml);
                // 最低还款金额
                var minPayment = billDateEveryDoc
                    .select(".tabA > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(4)")[0].text().trim()
                    .replaceAll(",", "");
                // 上期还款金额""
                var lastPayment = billDateEveryDoc.select(".w172")[0].text().trim().replaceAll(",", "");
                // 还款日""
                var paymentDate = billDateEveryDoc.select("td.c-red:nth-child(4)")[0].text().trim();
                // 本期应还金额
                var newBalance = billDateEveryDoc
                    .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1)")[0]
                    .text().trim().replaceAll(",", "");
                context.put("newBalance", newBalance);
                // 上期账单金额
                var lastBalance = billDateEveryDoc
                    .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(3)")[0]
                    .text().trim().replaceAll(",", "");
                // 本期帐单金额
                var newCharges = billDateEveryDoc
                    .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(7)")[0]
                    .text().trim().replaceAll(",", "");
                // 循环利息
                var interest = billDateEveryDoc
                    .select("div.pt10 > div:nth-child(2) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(11)")[0]
                    .text().trim();

                billAllData.setMinPayment(stringToBigDecimal(minPayment));
                billAllData.setLastPayment(!equals(lastPayment,"") ? stringToBigDecimal("-" + lastPayment) : null);
                if(!equals(paymentDate,"")){
                    billAllData.setPaymentDueDate(getDate(paymentDate,"yyyy-MM-dd"));
                }
                billAllData.setNewBalance(stringToBigDecimal(newBalance));
                billAllData.setLastBalance(stringToBigDecimal(lastBalance));
                billAllData.setNewCharges(stringToBigDecimal(newCharges));
                billAllData.setInterest(stringToBigDecimal(interest));
            }
            // billAllData.setInterest(null);
            billAllData.setUsdNewBalance(null);
            billAllData.setUsdLastBalance(null);
            billAllData.setUsdLastPayment(null);
            billAllData.setUsdNewCharges(null);
            billAllData.setUsdInterest(null);
            billAllData.setUsdCreditLimit(null);
            billAllData.setUsdCashLimit(null);
            billAllData.setUsdMinPayment(null);
            creditCardAllData.getBills().add(billAllData);
        }catch (e) {
            logger.error("北京银行信用卡,任务{}，抓取基本信息异常：{}", context.get(LUA_TASK_KEY), e);
            statCaughtException(context, e);
        }
    },
    /**
     * 抓取用户未出账单数据
     * @param creditCardAllData
     */
    crawlBillDetail: function(creditCardAllData,billAllData,singleMonth,doneType){
        logger.info("北京银行信用卡,任务{},开始抓取，{} 月已出账单数据", context.get(LUA_TASK_KEY),singleMonth);
        try{
            var billDateShoppingJson;
            if(equals("UNDONE",doneType)){
                billDateShoppingJson = context.get("bill_" + doneType +"_Shopping");
            }else {
                billDateShoppingJson = context.get("bill_" + doneType +"_"+ singleMonth + "Shopping");
            }
            if(!billDateShoppingJson.contains("[]")){

                var billDateShoppingJsonArray = JSON.parse(billDateShoppingJson);
                // var billDateShoppingJsonArray = JSON.toJavaObject(JSON.parseArray(billDateShoppingJsonArray), List.class);
                var mapListJson =  billDateShoppingJsonArray;
                //分期第一次出现的位置  如果小于 手续费第一次出现的位置   证明  分期在手续费前面
                //分期第一次出现的位置  如果大于 手续费第一次出现的位置    证明  分期在手续费后面 需要反转
                var fenqiIndex= mapListJson.toString().indexOf("分期") ;
                var shouxufeiIndex =  mapListJson.toString().indexOf("手续费");
                if(fenqiIndex > shouxufeiIndex){
                    Collections.reverse(mapListJson);
                }
                var index = 0;
                // json字符串的长度 相当于有多少条消费记录
                var originalNewCharges = 0.0;
                for (var i = 0; i < mapListJson.size(); i++) {
                    var expense = new Expense();
                    var jsonItemEveryDate = mapListJson.get(i);
                    // 卡号后四位
                    var cardNum = "";
                    var amountMoney = "";
                    var tranDESLINE1 = "";
                    var tranDESLINE2 = "";
                    var transDate = "";
                    // 金额
                    if(equals("UNDONE",doneType)){
                        cardNum = jsonItemEveryDate.get("cardEnd").trim();
                        //交易时间
                        transDate = jsonItemEveryDate.get("val_Date").trim();
                        //消费
                        amountMoney = jsonItemEveryDate.get("amount").trim().replaceAll(",", "");
                        //描述
                        tranDESLINE1 = jsonItemEveryDate.get("descline1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");
                        tranDESLINE2 = jsonItemEveryDate.get("descline2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                         if(StringUtils.isNotBlank(tranDESLINE1)){
                             if(tranDESLINE1.contains("还款")){
                                 billAllData.setLastPayment(stringToBigDecimal(amountMoney));
                             }
                         }
                    }else {
                        cardNum = jsonItemEveryDate.get("cardEND").trim();
                        amountMoney = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
                        // new_charges 页面上有  但不直接取值  因为页面上的值不准确 所以要计算
                        if(!amountMoney.contains("-")){
                            originalNewCharges = originalNewCharges +  Double.parseDouble(amountMoney);
                        }
                        // 描述
                        tranDESLINE1 = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                        tranDESLINE2 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                        // 交易日
                        transDate = jsonItemEveryDate.get("val_DATE").trim();
                    }
                    var description = tranDESLINE1 + tranDESLINE2;
                    logger.info("{},描述:{}", context.get(LUA_TASK_KEY), description);

                    //如果描述中出现账单分期手续费,就将分期手续费和描述用map集合装起来  待等到当前分期为1的时候再放进去
                    //因为这个分期手续费是总共的
                    if (description.contains("分期手续费")) {
                        logger.info("-----分期手续费:{}", description);
                        context.put("amountMoney", amountMoney);
                        context.put("description", description);
                    }
                    expense.setId(UUID.randomUUID().toString());
                    expense.setCardNum(cardNum);
                    expense.setBalance(null);
                    // 记帐日
                    expense.setPostDate(getDate(transDate,"yyyy-MM-dd"));
                    // 消费类型
                    expense.setCategory(CategoryUtil.getCreditCategory("BEIJING", description, amountMoney));
                    // 排序
                    expense.setOrderIndex(++index);
                    // 交易时间
                    expense.setTransDate(getDate(transDate,"yyyy-MM-dd"));
                    // 币种
                    expense.setCurrencyType("CNY");
                    // 消费金额
                    expense.setAmountMoney(stringToBigDecimal(amountMoney));
                    // 描述
                    expense.setDescription(description);
                    //对方持卡人
                    expense.setNameOnOppositeCard("");
                    //对方银行卡
                    expense.setOppositeBank("");
                    //对方卡号
                    expense.setOppositeCardNo("");
                    //备注
                    expense.setRemark("");
                    //交易通道
                    expense.setTransChannel("");
                    //交易方式
                    expense.setTransMethod("");
                    //交易地点
                    expense.setTransAddr("");
                    if (isNumExists(description) && (description.contains("账单分期") || description.contains("灵活分期") || (description.contains("灵动金") && !description.contains("手续费")))) {
                        logger.info("北京银行信用卡,任务{},开始抓取，{} 月已出账单分期数据", context.get(LUA_TASK_KEY),singleMonth);
                        if (getFen(description).size() > 1) {
                            var installment = new Installment();
                            billAllData.getInstallments().add(installment);
                            installment.setShoppingsheetId(UUID.randomUUID().toString());
                            //金额
                            installment.setAmountMoney(stringToBigDecimal(amountMoney));
                            //记帐日
                            installment.setPostDate(getDate(transDate,"yyyy-MM-dd"));
                            //交易日
                            installment.setTransDate(getDate(transDate,"yyyy-MM-dd"));
                            //分期描述
                            installment.setInstallmentDesc(description);
                            //分期转帐手续费描述
                            installment.setTransferfeeDesc("");
                            //分期类型
                            installment.setInstallmentType(installmentTypeChange(description));
                            //币种
                            installment.setCurrencyType(expense.getCurrencyType());
                            // 转账手续费
                            installment.setTransferFee(null);
                            if (getFen(description).size() == 2) {
                                //当前分期数
                                installment.setCurrentMonth(getFen(description).get(0));
                                // 总分期数
                                installment.setTotalMonth(getFen(description).get(1));
                            } else if (getFen(description).size() == 3) {//灵动金
                                //当前分期数
                                installment.setCurrentMonth(getFen(description).get(1));
                                // 总分期数
                                installment.setTotalMonth(getFen(description).get(2));
                            }
                            if (description.contains("账单分期") || description.contains("灵活分期")) {
                                //如果当前分期为1的时候 就把集合里的取出来    其他的是null
                                if (getFen(description).get(0) == 1) {
                                    if((i + 1) < mapListJson.size() ) {
                                        var jsonItemEveryDate = mapListJson.get(i + 1);
                                        var amountMoney1 = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
                                        var tranDESLINE = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                        var tranDESLINE3 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                        var insDes = tranDESLINE + tranDESLINE3;
                                        logger.info("{},下一条描述:{}",context.get(LUA_TASK_KEY),insDes);
                                        if (insDes.contains("手续费")) {
                                            //分期金额
                                            installment.setHandingFee(stringToBigDecimal(amountMoney1));
                                            //分期手续费描述
                                            installment.setHandingfeeDesc(insDes);
                                        }else {
                                            //分期金额
                                            installment.setHandingFee(null);
                                            //分期手续费描述
                                            installment.setHandingfeeDesc("");
                                        }
                                    }else if((i + 1) == mapListJson.size()){
                                        var jsonItemEveryDate = mapListJson.get(i);
                                        var amountMoney1 = jsonItemEveryDate.get("tranAMOUNT").replaceAll(",", "").trim();// -365.9
                                        var tranDESLINE = jsonItemEveryDate.get("tranDESLINE1").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                        var tranDESLINE3 = jsonItemEveryDate.get("tranDESLINE2").trim().replaceAll("\\u00A0", "").replaceAll("\\s*", "");// -365.9
                                        var insDes = tranDESLINE + tranDESLINE3;
                                        logger.info("{},上一条描述:{}",context.get(LUA_TASK_KEY),insDes);
                                        if (insDes.contains("手续费")) {
                                            //分期金额
                                            installment.setHandingFee(stringToBigDecimal(amountMoney1));
                                            //分期手续费描述
                                            installment.setHandingfeeDesc(insDes);
                                        }else {
                                            //分期金额
                                            installment.setHandingFee(null);
                                            //分期手续费描述
                                            installment.setHandingfeeDesc("");
                                        }
                                    }
                                }else {
                                    //分期金额
                                    installment.setHandingFee(null);
                                    //分期手续费描述
                                    installment.setHandingfeeDesc("");
                                }
                            }
                        }
                    } else if (description.contains("灵动金") && description.contains("手续费")) {
                        //判断分期费和分期手续费是不是同一个对象
                        var ins = findExistInstallment(billAllData.getInstallments(), description);
                        logger.info("灵动金的分期手续费描述:{},分期对象:{}", description, ins);
                        //是将分期的集合遍历一下 找到灵动金的分期   如果找到灵动金的分期描述   将判断分期描述的当期分期和灵动金的分期手续费描述当期不分期是不是同一个分期
                        //如果是同一个分期  就添加到
                        var list = billAllData.getInstallments();
                        for each(var in_fee in list) {
                            if (in_fee.getInstallmentDesc().contains("灵动金")) {

                                if (getFen(in_fee.getInstallmentDesc()).get(1) == getFen(description).get(1) && ins !== null) {
                                    ins.setHandingFee(expense.getAmountMoney());
                                    ins.setHandingfeeDesc(description);
                                }
                            }else{
                                ins.setHandingFee(!equals("",context.get("amountMoney")) && null !== context.get("amountMoney") ? stringToBigDecimal(context.get("amountMoney")) : null);
                                ins.setHandingfeeDesc(context.get("description"));
                            }
                        }
                    }

                    billAllData.getShoppingSheets().add(expense);
                }
                logger.info("{},setNewCharges={}",context.get(LUA_TASK_KEY),originalNewCharges);
                // billAllData.setNewCharges(stringToBigDecimal(String.format("%.2f",originalNewCharges)));
            }else{
                logger.info("北京银行信用卡,任务{},开始抓取，{} 月没有已出账单数据", context.get(LUA_TASK_KEY),singleMonth);
            }
        } catch (e) {
            logger.error("{}，北京银行信用卡{}账单抓取异常：{}", context.get(LUA_TASK_KEY), singleMonth, e);
            statCaughtException(context, e);
        }
    },
}
/**
 * 给已出账单中的分期找对应关系
 *
 * @param installments 是不包含手续费
 * @param description  包含手续费
 * @return
 */
function  findExistInstallment(installments,  description) {
    // TODO Auto-generated method stub
    for each(var installment in installments) {
        if (installment.getInstallmentDesc().contains("灵动金") && description.contains("灵动金")) {
            return installment;
        }
    }
    return null;
}
/**
 * 把分期描述里的数字提取出来或提取未出账单中的总页和当前页
 *
 * @param des
 * @return
 */
function   getFen(des) {
    var list = new ArrayList();
    var r = Pattern.compile("\\d+");
    var m = r.matcher(des);
    while (m.find()) {
        list.add(Integer.parseInt(m.group()));
    }
    return list;
}
/**
 * 卡号集合
 */
function cardListFunc(accountDoc) {
    var sb = new StringBuffer();
    //全部为数字的正则表达式
    var numStr = "^[0-9]*$";
    //判断有几个卡号
    var  cardSize = accountDoc.select(".sel > option").size();
    logger.info("{},==有{}个卡号", context.get(LUA_TASK_KEY),cardSize);
    for(var i = 1; i <= cardSize; i ++){
        var fullCardNum = accountDoc.select(".sel > option:nth-child("+i+")").text();
        //此处判断卡号是否包含*号,
        if(fullCardNum.contains("*") ){
            sb.append(fullCardNum).append(",");
        }
        //全部是数字
        if (fullCardNum.matches(numStr)){
            sb.append(fullCardNum).append(",");
        }
    }
    return sb.toString().substring(0,sb.toString().lastIndexOf(","));
}
/**
 * 卡后四位
 */
function cardNum(accountDoc) {
    var sb = new StringBuffer();
    //判断有几个卡号
    var  cardSize = accountDoc.select(".sel > option").size();
    context.put("creditCardSize",cardSize)
    logger.info("{},>>>>有{}个卡号", context.get(LUA_TASK_KEY),cardSize);
    for(var i = 1; i <= cardSize; i ++){
        var fullCardNum = accountDoc.select(".sel > option:nth-child("+i+")").text();
        logger.info("{},第{}个卡号:{}",context.get(LUA_TASK_KEY),i,fullCardNum)
        if(fullCardNum.contains("*")){
            sb.append(fullCardNum.substring((fullCardNum.length() - 4), (fullCardNum.length()))).append(",");
        }

    }
    return sb.toString().substring(0,sb.toString().lastIndexOf(","));
}
/**
 * 判断字符串里面是否包含数字
 *
 * @param description
 * @return
 */
function isNumExists(description) {

    return description.matches(".*\\d+.*");
}
// 根据中文币种生成英文币种
function   installmentTypeChange(type) {
    if (type.contains("账单")) {
        return "BILL";
    } else if (type.contains("现金")) {
        return "CASH";
    } else if (type.contains("消费") || type.contains("苹果") || type.contains("新兴业")) {
        return "CONSUME";
    } else {
        return "CONSUME";
    }
}